using GrpcClient.Managers;
using GrpcClient.Models;
using GrpcClient.Services;
using System.Configuration;
using System.Diagnostics;
using System.Windows;
using XAliphant.Net.Client;

namespace GrpcClient
{
    public class ResourceManager : ClientBase
    {
        private static ResourceManager? _instance;
        public static ResourceManager Instance => _instance ?? (_instance = new ResourceManager());

        public readonly string ip = ConfigurationManager.AppSettings["Ip"];
        public readonly string port = ConfigurationManager.AppSettings["Port"];
        private CancellationTokenSource? cts = new CancellationTokenSource();

        public event Action<string>? UpdateLoadingMessageEvent;

        private ResourceDictionary? Resource { get; set; }
        private string? Uri { get; set; }

        public WindowState LastState { get; set; }

        public string MainPage { get; set; } = ConfigurationManager.AppSettings["MainPage"];


        public async Task Loading()
        {
            GetTheme();

            UpdateLoadingMessage("正在连接...");
            await Task.Run(() =>
            {
                Connect();

                Task.Factory.StartNew(() =>
                {
                    while (!(cts?.IsCancellationRequested ?? true))
                    {
                        try
                        {
                            Update();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            Thread.Sleep(1000);
                        }
                    }
                });
            });

            Start();
        }

        public override void Connect()
        {
            Debug.WriteLine($"Connect to {ip}:{port}");
            base.Connect();

            if (!IsConnected)
            {
                MessageBox.Show("未连接服务器");
            }

            UpdateLoadingMessage("");
        }

        public override void Start()
        {
            TabManager.Instance.Init();

            UserService.Instance.Start();
            UserManager.Instance.Start();
        }

        public override void Stop()
        {
            UserManager.Instance.Stop();
            UserService.Instance.Stop();
        }

        public override void Exit()
        {
            base.Exit();
            cts?.Cancel();
        }

        public void UpdateLoadingMessage(string message)
        {
            if (UpdateLoadingMessageEvent != null)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    UpdateLoadingMessageEvent(message);
                });
            }
        }

        public override string Ip => ip;

        public override string Port => port;

        public ThemeType CurrentTheme { get; private set; }

        public void SetTheme(ThemeType theme)
        {
            if (this.Uri == null)
            {
                ResourceDictionary resourceDictionary = Application.Current.Resources.MergedDictionaries[0];
                string path = resourceDictionary.Source.AbsolutePath;
                this.Uri = path.Remove(path.LastIndexOf("/"));
            }

            string target = $"{Uri}/{theme}.xaml";
            this.Resource = (ResourceDictionary)Application.LoadComponent(new Uri(target, UriKind.RelativeOrAbsolute));
            Application.Current.Resources.MergedDictionaries.RemoveAt(1);//移出第0个元素
            Application.Current.Resources.MergedDictionaries.Insert(1, Resource);

            if (CurrentTheme != theme)
            {
                CurrentTheme = theme;

                SaveTheme();
            }
        }

        private void SaveTheme()
        {
            ConfigContainer.Instance.cacheManager.Set("theme", (int)CurrentTheme);
        }

        private void GetTheme()
        {
            ConfigContainer.Instance.cacheManager.Get("theme", out int index);
            CurrentTheme = (ThemeType)index;
            SetTheme(CurrentTheme);
        }
    }
}
